/*
 * create:2016年4月5日 上午10:59:46
 * author:wangds  
 */
package com.cxkj.shop.biz;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpSession;

import com.cxkj.shop.model.order.Order;
import com.cxkj.shop.model.order.OrderItem;
import com.cxkj.shop.model.user.User;
import com.cxkj.shop.utils.BusinessUtils;
import com.cxkj.shop.utils.IpUtils;
import com.cxkj.shop.utils.OrderUtils;
import com.cxkj.shop.utils.UserUtils;
import com.cxkj.shop.utils.WeiXinHttpsUtils;
import com.cxkj.shop.utils.WxSignUtils;
import com.cxkj.shop.utils.WxUnifiedOrderUtils;

import net.wangds.comp.business.http.AbstractHttpInteractionBusiness;
import net.wangds.utilities.lang.StringUtils;

/**
 * 支付申请.
 * @author wangds
 *
 */
public class CreateAnOrderBusiness extends AbstractHttpInteractionBusiness<Map<String,Object>, Map<String,Object>> {

  private static final String _MD5 = "7M7ZitatWqJxwUnVFPetdiX0Ic5YqLIa";//商户平台里面的迷药
  private static final String RETURN_CODE = "<return_code>SUCCESS";
  private static final String RETURN_CODE_CDATA = "<return_code><![CDATA[SUCCESS]]>";
  private static final String RETURN_CODE_E = "</return_code>";
  private static final String RETURN_CODE_B = "<return_code>";
  private static final String CDATA_E = "]]>";
  private static final String CDATA_B = "<![CDATA[";
  private static final String PREPAY_ID_E = "</prepay_id>";
  private static final String PREPAY_ID_B = "<prepay_id>";
  private static final String PAY_SIGN = "paySign";
  private static final String APP_ID = "appId";

  private static final String RESULT = "result";

  private static final String URL_WEIXIN = "https://api.mch.weixin.qq.com/pay/unifiedorder";

  private static final String MD5 = "MD5";

  private static final String SIGN_TYPE = "signType";

  private static final String PREPAY_ID = "prepay_id=";

  private static final String PACKAGE = "package";

  private static final String NONCE_STR = "nonceStr";

  private static final String TIME_STAMP = "timeStamp";

  private static final String APP_ID_VALUE = "wx5c303dff15810ad4";//"wxcfaade2adf65b9ef";

  private static final String URL_GEGEWU = "http://gegewu.net.cn/shop/fn/payCallback";

  //private static final String OPENID = "openid";

  private static final String DEFAULT_DATE_FORMAT = "yyyyMMddHHmmssSSS";

  private static final String DEFAULT_MCH_ID = "1327071801";//"1315836001";//微信支付商户id

  /*
   * @see net.wangds.common.processor.Processor#process()
   * 
   * @author wangds 2016年4月5日 上午11:00:17.
   */
  @Override
  public void process() {

    try {
      //HttpServletRequest req = this.getHttpRequest();

      //HttpSession session = req.getSession();

      //Map<String, Object> map_usr = (Map<String, Object>) session.getAttribute(FillUserServlet.CONSTANTS.KEY_SESSION_USERINFO_MAP);

      String ip = IpUtils.getIpAddr(this.getHttpRequest());
      String mchId = DEFAULT_MCH_ID;
      SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
      
      Map<String,Object> input = this.getInput();
      String order_id = String.valueOf(input.get("orderId"));
      
      
      Order order = OrderUtils.queryOrderByOrderId(order_id);
      int pay = order.getPay();
      
      if(pay==0){
        onPayZero(order);
        return;
      }
      
      
      String orderId = order.getOrderId();
      String address = order.getAddress();
      String receiverName = order.getReceiverName();
      String postCode = order.getPostCode();
      String phone = order.getPhone();
      
      String att = StringUtils.join(receiverName," ",phone,",",address," ",postCode);
      StringBuffer buf = new StringBuffer();
      Collection<OrderItem> items = order.getItems();
      
      int c = 0;
      for(OrderItem cur:items){
        buf.append(cur.getCommodityName()).append(":")
          .append(cur.getScore()).append("*")
          .append(cur.getAmount())
          .append("[").append(cur.getScore()).append("];");
        c+=((Number)cur.getAmount()).intValue();
      }
      String detail = buf.toString();
      
      String body = items.size()+"种"+c+"件商品，共计"+pay+"分@"+sdf.format(new Date());
      String openId = BusinessUtils.getOpenIdSession(BusinessUtils.getHttpSessionFromHttpBusiness(this));
      String xml = WxUnifiedOrderUtils.unifiedOrderXml(
          openId, APP_ID_VALUE, mchId, ip,
          orderId, Integer.toString(pay), URL_GEGEWU, body, detail, att);
      
      String res_xml = WeiXinHttpsUtils.httpsPost(URL_WEIXIN, xml);
      this.getLogger().info("Wiexin prepay res xml:"+res_xml);
      Map<String, Object> r = new HashMap<String, Object>();
      
      if (isOk(res_xml)) {
        TreeMap<String, Object> sign_map = new TreeMap<String, Object>();
        String prepayId = cutPrepayId(res_xml);
        r.put(RESULT, true);
        r.put(APP_ID, APP_ID_VALUE);
        sign_map.put(APP_ID, r.get(APP_ID));
        r.put(TIME_STAMP, WxSignUtils.getTimeStamp());
        sign_map.put(TIME_STAMP, r.get(TIME_STAMP));
        r.put(NONCE_STR, WxSignUtils.getNonceStr());
        sign_map.put(NONCE_STR, r.get(NONCE_STR));
        r.put(PACKAGE, PREPAY_ID + prepayId);
        sign_map.put(PACKAGE, r.get(PACKAGE));
        r.put(SIGN_TYPE, MD5);
        sign_map.put(SIGN_TYPE, r.get(SIGN_TYPE));
        r.put(PAY_SIGN, WxSignUtils.createSign(sign_map, _MD5));
      } else {
        r.put(RESULT, false);
      }

      this.setOutput(r);
    } catch (Exception e) {
      this.getLogger().error(e.getMessage(), e);
    }

  }

  /**
   * .
   * @author wangds 2016年5月9日 上午1:19:13.
   */
  private void onPayZero(Order order) {
    Map<String, Object> r = new HashMap<String, Object>();
    r.put("sysFlag", "zero");
    HttpSession ssn = BusinessUtils.getHttpSessionFromHttpBusiness(this);
    String openId = BusinessUtils.getOpenIdSession(ssn);
    User u = UserUtils.selectUserByOpenId(openId);
    UserUtils.addUserBalance(u, -order.getBalance());
    OrderUtils.updateOrderOnPayZero(order);
    this.setOutput(r);
  }

  /**
   * .
   * 
   * @author wangds 2016年4月7日 上午11:14:20.
   * @param res_xml
   * @return
   */
  private String cutPrepayId(String xml) {
    int idx_s = xml.indexOf(PREPAY_ID_B);
    int idx_e = xml.indexOf(PREPAY_ID_E);
    String sub = xml.substring(idx_s, idx_e);
    sub = sub.substring(PREPAY_ID_B.length());
    if (sub.startsWith(CDATA_B) && sub.endsWith(CDATA_E)) {
      sub = sub.substring(CDATA_B.length(), sub.length() - 3);
    }
    return sub;
  }

  /**
   * .
   * 
   * @author wangds 2016年4月7日 上午11:07:03.
   * @param res_xml
   * @return
   */
  private boolean isOk(String xml) {
    boolean res = false;
    if (StringUtils.isBlank(xml)) {
      return res;
    }
    int idx_s = xml.indexOf(RETURN_CODE_B);
    int idx_e = xml.indexOf(RETURN_CODE_E);
    String sub = xml.substring(idx_s, idx_e);
    res = (RETURN_CODE_CDATA.equals(sub) || RETURN_CODE.equals(sub));
    return res;
  }
  

}
